#include <stdio.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>

#define BUFFER_SIZE 256

void error(char *msg)
{
	perror(msg);
	exit(1);
}

int main(int argc, char *argv[])
{
	int sockfd, portno, n;
	socklen_t serv_length;
	struct sockaddr_in serv_addr;
	struct hostent *server;
	char buffer[BUFFER_SIZE];

	if(argc < 3) {
		fprintf(stderr,"usage: %s <server ip> <port no>\n", argv[0]);
		exit(1);
	}

	server = gethostbyname(argv[1]);
	if(server == NULL)
		error("ERROR: failed to fetch host info\n");

	portno = atoi(argv[2]);

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sockfd < 0)
		error("ERROR: Failed to create client socket\n");

	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	bcopy((char *) server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length);
	serv_addr.sin_port = portno;

	printf("Enter your message: ");
	bzero(buffer, BUFFER_SIZE);
	fgets(buffer, BUFFER_SIZE-1, stdin);

	serv_length = sizeof(struct sockaddr_in);

	n = sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *) &serv_addr, serv_length);
	if(n < 0)
		error("ERROR: Failed to send message to the server");

	n = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *) &serv_addr, &serv_length); 	
	if(n < 0)
		error("ERROR: Failed to receive message from the server");

	printf("Server Repies: %s", buffer);

	return 0;
}
